package com.fare.taluo.core.domain.repository.impl;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.hadoop.hbase.filter.Filter;
import org.springframework.stereotype.Repository;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.GlobalsConst;
import com.fare.taluo.base.ddd.repository.EntityHibernateRepository;
import com.fare.taluo.core.domain.entity.crawl.FreightPriceEntity;
import com.fare.taluo.core.domain.repository.IFreightRepository;
import com.fare.taluo.db.hbase.HBaseCellModel;
import com.fare.taluo.db.hbase.HBaseRowModel;
import com.fare.taluo.db.hbase.HbaseManager;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.util.RegHtmlUtil;
import com.fare.taluo.util.StringAndDateAndFileUtil;
import com.fare.taluo.util.StringUtils;
import com.fare.taluo.vo.airfreight.StopOverEntityVO;
import com.fare.taluo.vo.airfreight.doub.CabinRelationEntityVO;
import com.fare.taluo.vo.core.AgentInfo;
import com.fare.taluo.vo.core.CabinEntityVO;
import com.fare.taluo.vo.core.HBaseFilterVO;
import com.fare.taluo.vo.core.PlaneInfo;
import com.fare.taluo.vo.core.ReturnTripEntityVO;
import com.fare.taluo.vo.core.TransitchangeEntityVO;
import com.foreveross.crawl.domain.freight.CabinEntity;
import com.foreveross.crawl.domain.freight.ReturnTripEntity;
import com.foreveross.crawl.domain.freight.TransitchangeEntity;
@Repository
public class FreightRepositoryImpl extends EntityHibernateRepository implements IFreightRepository {
	private static Map<String,Method> planeInfoMethods = new HashMap<String, Method>();
	private static Map<String,Method> agentMethods = new HashMap<String, Method>(); 
	private static Map<String,Method> cabinMethods = new HashMap<String, Method>(); 
	private static Map<String,Method> stopOverMethods = new HashMap<String, Method>(); 
	private static Map<String,Method> transitMethods = new HashMap<String, Method>(); 
	private static Map<String,Method> cabinRelationMethods = new HashMap<String, Method>(); 
	
	
	
	
	static{
		Method[] planeInfoMs = PlaneInfo.class.getMethods();
		for (Method m : planeInfoMs) {
			planeInfoMethods.put(m.getName(), m);
		}
		Method[] agentMs = AgentInfo.class.getMethods();
		for (Method m : agentMs) {
			agentMethods.put(m.getName(), m);
		}
		Method[] cabinMs = CabinEntityVO.class.getMethods();
		for (Method m : cabinMs) {
			cabinMethods.put(m.getName(), m);
		}
		Method[] stopOverMs = StopOverEntityVO.class.getMethods();
		for (Method m : stopOverMs) {
			stopOverMethods.put(m.getName(), m);
		}
		Method[] transitMs = TransitchangeEntityVO.class.getMethods();
		for (Method m : transitMs) {
			transitMethods.put(m.getName(), m);
		}
		Method[] cabinRelationMs = CabinRelationEntityVO.class.getMethods();
		for (Method m : cabinRelationMs) {
			cabinRelationMethods.put(m.getName(), m);
		}
		
		
	}
	@Override
	public List<FreightPriceEntity> findByConditions(String tableName,
			String startRowKey, String endRowKey) throws Exception {
		HbaseManager hbaseManager = null;
		try {
	    	 hbaseManager = InstanceFactory.getInstance(HbaseManager.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Method[] planeInfoMs = FreightPriceEntity.class.getMethods();
		List<HBaseRowModel> list = null;
		try {
			//获得多个HBaseRowModel,HBaseRowModel相当于一行
			list = hbaseManager.getMultRecord(tableName, startRowKey, endRowKey);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<FreightPriceEntity> results = new ArrayList<FreightPriceEntity>();
        
		//将HBaseRowModel转换成FreightPriceEntity保存在results中
		for(HBaseRowModel model : list){
			FreightPriceEntity entity = new FreightPriceEntity();
			Set<HBaseCellModel> cellSet = model.getCells();
			//仓位
			Set<CabinEntity> cabinSet = this.getCabinEntitySet(cellSet);
			//中转
			List<TransitchangeEntity> transit = this.getTransitchangeEntityList(cellSet);
			//获得返程
			List<ReturnTripEntity> returnTripEntityList = new ArrayList<ReturnTripEntity>();
			returnTripEntityList.addAll(this.getReturnTripEntitySet(cellSet));
			//List<ReturnTripEntityVO> returnTripVOList = this.getReturnTripEntity2VO(returnTripEntityList);
			//对每一列操作
			for(HBaseCellModel cell : model.getCells()){
				for (Method method : planeInfoMs) {
					String tmp = method.getName();
					if(tmp.startsWith("set")&&tmp.equals("set"
												+ cell.getQualifier().substring(0, 1)
														.toUpperCase()
												+ cell.getQualifier().substring(1))&& !tmp.equals("setCabins")){
						
						if(method.getParameterTypes().length>0 && method.getParameterTypes()[0].getName().contains("Double")){
							//对Double类型转换
							method.invoke(entity, Double.parseDouble(cell.getValue()));
						}else if(method.getParameterTypes().length>0&&method.getParameterTypes()[0].getName().contains("Long")){
							//对Long类型转换
							method.invoke(entity, Long.parseLong(cell.getValue()));
						}else{
							method.invoke(entity, cell.getValue());
						}
					}else if(tmp.startsWith("set") && tmp.equals("setCabins")){
						entity.setCabins(cabinSet);
					}else if(tmp.startsWith("set") && tmp.equals("setTransit")){
						entity.setTransit(transit);
					}else if(tmp.startsWith("set") && tmp.equals("setSourceRowkey") && cell.getQualifier().equals("SOURCE_ROWKEY")){
						method.invoke(entity, cell.getValue());
					}else if(tmp.startsWith("set") && tmp.equals("setStartTime") && cell.getQualifier().equals("flightBatchStartTime")){
						method.invoke(entity, DateUtils.parseDate(cell.getValue(), "yyyyMMddHHmmss"));		
					}else if(tmp.startsWith("set") && tmp.equals("setCreateTime") && cell.getQualifier().equals("grabDate")){
						method.invoke(entity, DateUtils.parseDate(cell.getValue(), "yyyyMMddHHmmssSSS"));		
					}
						
						
				}			
			}
			entity.setReturnTrip(returnTripEntityList);
			results.add(entity);
		}
		
		return results;
	}
	
	
	@Override
	public List<PlaneInfo> findByConditionsToPlaneInfo(String tableName,
			String startRowKey, String endRowKey, List<Filter> filterList){
		HbaseManager hbaseManager = null;
		try {
	    	 hbaseManager = InstanceFactory.getInstance(HbaseManager.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Method[] planeInfoMs = FreightPriceEntity.class.getMethods();
		List<HBaseRowModel> list = null;
		try {
			//获得多个HBaseRowModel,HBaseRowModel相当于一行
			list = hbaseManager.getMultRecord(tableName, startRowKey, endRowKey,filterList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//---------------------------------------------------------------------
		List<PlaneInfo> result = new ArrayList<PlaneInfo>();
		String qualifier,value,family;
		String[] agentInfoKey;
		for (HBaseRowModel model : list) {
			Set<HBaseCellModel> cellSet = model.getCells();
			//获得仓位
			List<CabinEntity> cabinTempList = new ArrayList<CabinEntity>();
			cabinTempList.addAll(this.getCabinEntitySet(cellSet));
			List<CabinEntityVO> cabinSet = this.cabinEntity2VO(cabinTempList);
			//获得中转
			List<TransitchangeEntityVO> transit = this.TransitchangeEntity2VO(this.getTransitchangeEntityList(cellSet));
			//获得代理商
			List<AgentInfo> agents = new ArrayList<AgentInfo>();
			Map<String,AgentInfo> agentMap = new HashMap<String, AgentInfo>();
			//获得返程
			List<ReturnTripEntity> returnTripEntityList = new ArrayList<ReturnTripEntity>();
			returnTripEntityList.addAll(this.getReturnTripEntitySet(cellSet));
			List<ReturnTripEntityVO> returnTripVOList = this.getReturnTripEntity2VO(returnTripEntityList);
			
			PlaneInfo planeInfo = new PlaneInfo();
			try {
				for (HBaseCellModel cell : model.getCells()) {
					qualifier = cell.getQualifier();
					family = cell.getFamily();
					value = cell.getValue();
					if ("planeinfo".equals(family)) {
						Method method = planeInfoMethods.get("set" + qualifier.substring(0, 1).toUpperCase()+ qualifier.substring(1));
						if(null != method){
							try{
								method.invoke(planeInfo, value);
							} catch (Exception e) {
								logger.error(e.getMessage());
							}
						}
					}else if ("agentInfos".equals(family)) {
						agentInfoKey = cell.getQualifier().split("_");
						String property = agentInfoKey[0];
						String str = agentInfoKey[1];
						Method method = agentMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!agentMap.containsKey(str)) {
								agentMap.put(str, new AgentInfo());
							}
							if (agentMap.keySet().contains(str)) 
								try{
									method.invoke(agentMap.get(str),cell.getValue());
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
					}
				}
				
				planeInfo.setCabins(cabinSet);
				planeInfo.setTransit(transit);	
				agents.addAll(agentMap.values());
				planeInfo.setAgentInfos(agents);
				planeInfo.setReturnTrip(returnTripVOList);
				result.add(planeInfo);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	private List<TransitchangeEntity> getTransitchangeEntityList(Set<HBaseCellModel> cellSet){
				//对中转信息组织
				//找出中转最大的序号
				int max = 0;
				for (HBaseCellModel cell: cellSet) {
					String qualifier = cell.getQualifier();
					if(qualifier.startsWith("transit")){
					  int num = Integer.parseInt(qualifier.split("_")[1]);
					  if(num > max){
						  max = num;
					  }
					  
					}
				}
				
				List<TransitchangeEntity> transitList = new ArrayList<TransitchangeEntity>();		
				for (int i = 0; i < max+1; i++) {
					transitList.add(new TransitchangeEntity());
				}		
				for (HBaseCellModel cell : cellSet) {
					String qualifier = cell.getQualifier();
					if (qualifier.startsWith("transit")) {
						int index = Integer.parseInt(qualifier.split("_")[1]);
//						String cabinFlag = qualifier.split("_")[0];
						transitList.get(index).setFlag(true);
						if(qualifier.startsWith("transitCarrierFullName")){
							transitList.get(index).setCarrierFullName(cell.getValue());
						}else if(qualifier.startsWith("transitCarrierKey")){
							transitList.get(index).setCarrierKey(cell.getValue());
						}else if(qualifier.startsWith("transitCarrierName")){
							transitList.get(index).setCarrierName(cell.getValue());
						}else if(qualifier.startsWith("transitEndTime")){
							transitList.get(index).setEndTime(cell.getValue());
						}else if(qualifier.startsWith("transitFlightTyte")){
							transitList.get(index).setFlightTyte(cell.getValue());
						}else if(qualifier.startsWith("transitFromAir")){
							transitList.get(index).setFromAir(cell.getValue());
						}else if(qualifier.startsWith("transitHightPrice")){
							if(StringAndDateAndFileUtil.checkString(cell.getValue())){
								transitList.get(index).setHightPrice(Double.parseDouble(cell.getValue()));
							}else{
								transitList.get(index).setHightPrice(0d);
							}
						}else if(qualifier.startsWith("transitLowerPrice")){
							if(StringAndDateAndFileUtil.checkString(cell.getValue())){
								transitList.get(index).setLowerPrice(Double.parseDouble(cell.getValue()));
							}else{
								transitList.get(index).setLowerPrice(0d);
							}
							
						}else if(qualifier.startsWith("transitStartTime")){
							transitList.get(index).setStartTime(cell.getValue());
						}else if(qualifier.startsWith("transitToAir")){
							transitList.get(index).setToAir(cell.getValue());
						}else if(qualifier.startsWith("transitFlightNo")){
							transitList.get(index).setFlightNo(cell.getValue());
						}
							
					}
				}
			
				
				List<TransitchangeEntity> list = new ArrayList<TransitchangeEntity>();	
				for (TransitchangeEntity transitchangeEntity : transitList) {
					if(transitchangeEntity.isFlag()){
						list.add(transitchangeEntity);
					}
				}
			return list;
	}
	
	private Set<CabinEntity> getCabinEntitySet(Set<HBaseCellModel> cellSet){
		//对仓位信息组织
		//找出仓位最大的序号
		int max = 0;
		for (HBaseCellModel cell: cellSet) {
			String qualifier = cell.getQualifier();
			if(qualifier.startsWith("cabin")){
			  int num = Integer.parseInt(qualifier.split("_")[2]);
			  if(num > max){
				  max = num;
			  }
			  
			}
		}
		//生成max个cabin并放到一个set中
//		Set<CabinEntity> cabins = new HashSet<CabinEntity>();
		
		List<CabinEntity> cabinList = new ArrayList<CabinEntity>();
		
		for (int i = 0; i < max+1; i++) {
			cabinList.add(new CabinEntity());
		}
	
		for (HBaseCellModel cell : cellSet) {
			String qualifier = cell.getQualifier();
			if (qualifier.startsWith("cabin")) {
				int index = Integer.parseInt(qualifier.split("_")[2]);
				cabinList.get(index).setFlag(true);
				if(qualifier.startsWith("cabin_name")){
					cabinList.get(index).setCabinName(cell.getValue());
				}else if(qualifier.startsWith("cabin_no")){
					cabinList.get(index).setCabinNo(cell.getValue());
				}else if(qualifier.startsWith("cabin_price")){
					String price = null;
					if(cell.getValue().contains("￥")){
						price = cell.getValue().replace("￥", "");
					}else{
						price = cell.getValue();
					}
					if(!price.contains(",")){
						cabinList.get(index).setPrice(price.trim());
					}
					
				}else if(qualifier.startsWith("cabin_type")){
					cabinList.get(index).setCabinType(cell.getValue());
				}else if(qualifier.startsWith("cabin_rebate")){
					cabinList.get(index).setCabinRebate(Double.parseDouble(cell.getValue()));
				}else if(qualifier.startsWith("cabin_server")){
					cabinList.get(index).setCabinServer(cell.getValue());
				}
					
			}else if(qualifier.startsWith("lever")){
				int index = Integer.parseInt(qualifier.split("_")[1]);
				String cabinFlag = qualifier.split("_")[0];
				cabinList.get(index).setLevel(Integer.valueOf(cell.getValue()));
			}else if(qualifier.startsWith("product_name")){
				int index = Integer.parseInt(qualifier.split("_")[2]);
				cabinList.get(index).setProductName(cell.getValue());			
			}
		}
		
		//
		Set<CabinEntity> cabinToList = new HashSet<CabinEntity>();
		for (CabinEntity cabin : cabinList) {
			if(cabin.isFlag()){
				cabinToList.add(cabin);
			}
		}
		return cabinToList;
	}
	
	private Set<ReturnTripEntity> getReturnTripEntitySet(Set<HBaseCellModel> cellSet){
				//对返程信息组织
				//找出返程中最大的序号
				int max = 0;
				for (HBaseCellModel cell: cellSet) {
					String qualifier = cell.getQualifier();
					if(qualifier.startsWith("returnTrip")){
					  int num = Integer.parseInt(qualifier.split("_")[1]);
					  if(num > max){
						  max = num;
					  }
					  
					}
				}

				
				List<ReturnTripEntity> returnTripEntityList = new ArrayList<ReturnTripEntity>();
				
				for (int i = 0; i < max+1; i++) {
					returnTripEntityList.add(new ReturnTripEntity());
				}
			
				for (HBaseCellModel cell : cellSet) {
					
					String qualifier = cell.getQualifier();
					if (qualifier.startsWith("returnTrip") || qualifier.startsWith("totalPrice")) {
						int index = Integer.parseInt(qualifier.split("_")[1]);
						//returnTripEntityList.get(index).setFlag(true);
						if(qualifier.startsWith("returnTripCarrierFullName")){
							returnTripEntityList.get(index).setCarrierFullName(cell.getValue());
						}else if(qualifier.startsWith("returnTripCarrierName")){
							returnTripEntityList.get(index).setCarrierName(cell.getValue());
						}else if(qualifier.startsWith("returnTripFlightBatchDate")){
							returnTripEntityList.get(index).setFlightDate(cell.getValue());
							
						}else if(qualifier.startsWith("returnTripFlightBatchEndTime")){
							//returnTripEntityList.get(index).setEndTime(endTime)
						}else if(qualifier.startsWith("returnTripFlightBatchStartTime")){
							//returnTripEntityList.get(index).setStartTime(cell.getValue());
						}else if(qualifier.startsWith("returnTripFlightNo")){
							returnTripEntityList.get(index).setFlightNo(cell.getValue());
						}else if(qualifier.startsWith("returnTripFromAir")){
							returnTripEntityList.get(index).setFromAir(cell.getValue());
						}else if(qualifier.startsWith("returnTripFromCityCode")){
							returnTripEntityList.get(index).setFromCity(cell.getValue());
						}else if(qualifier.startsWith("returnTripFromCityName")){
							returnTripEntityList.get(index).setFromCityName(cell.getValue());
						}else if(qualifier.startsWith("returnTripToAir")){
							returnTripEntityList.get(index).setToAir(cell.getValue());
						}else if(qualifier.startsWith("returnTripToCityCode")){
							returnTripEntityList.get(index).setToCity(cell.getValue());
						}else if(qualifier.startsWith("returnTripToCityName")){
							returnTripEntityList.get(index).setToCityName(cell.getValue());
						}else if(qualifier.startsWith("totalPrice")){
							/*returnTripEntityList.get(index).setTotalPrice(cell.getValue()==""||cell.getValue()==null?0.0:Double.parseDouble(cell.getValue()));*/
							returnTripEntityList.get(index).setTotalPrice(Double.parseDouble(cell.getValue()));
						}
							
					}
				}
				
				//
				Set<ReturnTripEntity> returnTripList = new HashSet<ReturnTripEntity>();
				for (ReturnTripEntity cabin : returnTripEntityList) {
					//if(cabin.isFlag()){
					returnTripList.add(cabin);
					//}
				}
				return returnTripList;
	}
    private List<CabinEntityVO> cabinEntity2VO(List<CabinEntity> entityList){
    	List<CabinEntityVO> cabinVOList = new ArrayList<CabinEntityVO>();
    	String price = null;
    	CabinEntityVO vo = null;
    	try{
	    	for (CabinEntity cabinEntity : entityList) {
				 vo = new CabinEntityVO();
				vo.setCabinName(cabinEntity.getCabinName());
				vo.setCabinNo(cabinEntity.getCabinNo());
				vo.setCabinRebate(cabinEntity.getCabinRebate());
				vo.setCabinServer(cabinEntity.getCabinServer());
				vo.setCabinType(cabinEntity.getCabinType());
				vo.setProductName(cabinEntity.getProductName());
				if(org.apache.commons.lang3.StringUtils.isBlank(cabinEntity.getPrice())){
					continue;
				}
				if(NumberUtils.isNumber(cabinEntity.getPrice())){
					price = cabinEntity.getPrice();
				}else{
					price = RegHtmlUtil.regStr(cabinEntity.getPrice(), "\\d+",0);
				}
				if(org.apache.commons.lang3.StringUtils.isBlank(price)){
					continue;
				}
				vo.setPrice(Double.valueOf(price));
				cabinVOList.add(vo);
				
			}
    	}finally{
    		price = null;
    		vo = null;
    	}
    	return cabinVOList;
    }
    
    private List<CabinEntityVO> cabinEntity2VOForNewModel(List<com.foreveross.crawl.domain.airfreight.CabinEntity> entityList){
    	List<CabinEntityVO> cabinVOList = new ArrayList<CabinEntityVO>();
    	Double price = null;
    	CabinEntityVO vo = null;
    	try{
	    	for (com.foreveross.crawl.domain.airfreight.CabinEntity cabinEntity : entityList) {
				 vo = new CabinEntityVO();
				vo.setCabinName(cabinEntity.getSubCabinName());
				//vo.setCabinNo(cabinEntity.get);
				vo.setCabinRebate(cabinEntity.getRebate());
				vo.setCabinType(cabinEntity.getCabinType());
				vo.setProductName(cabinEntity.getProductName());
				vo.setPrice(cabinEntity.getPrice());
				vo.setLastSeatInfo(cabinEntity.getLastSeatInfo());
				vo.setMileageRatio(cabinEntity.getMileageRatio());
				vo.setOriginalPrice(cabinEntity.getOriginalPrice());
				vo.setTuigaiqian(cabinEntity.getTuigaiqian());
				vo.setZhijian(cabinEntity.getZhijian());
				cabinVOList.add(vo);
				
			}
    	}finally{
    		price = null;
    		vo = null;
    	}
    	return cabinVOList;
    }
   private List<ReturnTripEntityVO> getReturnTripEntity2VO( List<ReturnTripEntity> returnTripEntityList){
	   List<ReturnTripEntityVO> returnTripVOListTemp = new ArrayList<ReturnTripEntityVO>();
	   for (ReturnTripEntity returnTripEntity : returnTripEntityList) {
		   ReturnTripEntityVO vo = new ReturnTripEntityVO();
		   vo.setCarrierFullName(returnTripEntity.getCarrierFullName());
		   vo.setCarrierKey(returnTripEntity.getCarrierKey());
		   vo.setCarrierName(returnTripEntity.getCarrierName());
		 //  vo.setEndTime(returnTripEntity.getEndTime);
		   vo.setFlightDate(returnTripEntity.getFlightDate());
		 //  vo.setFlightNo(returnTripEntity.getFlightNo);
		   vo.setFromAir(returnTripEntity.getFromAir());
		   vo.setFromCity(returnTripEntity.getFromCity());
		   vo.setFromCityName(returnTripEntity.getFromCityName());
		   vo.setStartTime(returnTripEntity.getStartTime());
		   vo.setToAir(returnTripEntity.getToAir());
		   vo.setToCity(returnTripEntity.getToCity());
		   vo.setToCityName(returnTripEntity.getToCityName());
		   vo.setTotalPrice(returnTripEntity.getTotalPrice());
		  vo.setFlightNo(returnTripEntity.getFlightNo());
		   
		   returnTripVOListTemp.add(vo);
		   
		   
	   }
	   
	   
	   return returnTripVOListTemp;
   }
    
   private List<TransitchangeEntityVO> TransitchangeEntity2VO(List<TransitchangeEntity> entityList){
	   List<TransitchangeEntityVO> transitVOList = new ArrayList<TransitchangeEntityVO>();
	   for (TransitchangeEntity entity : entityList) {
		   TransitchangeEntityVO vo = new TransitchangeEntityVO();
		     vo.setEndTime(entity.getEndTime());
			vo.setFlightTime(entity.getFlightTime());
			vo.setFlightTyte(entity.getFlightTyte());
			vo.setFromAir(entity.getFromAir());
			vo.setFromCity(entity.getFromCity());
			vo.setFromCityCode(entity.getFromCityCode());
			vo.setHightPrice(entity.getHightPrice());
			vo.setLowerPrice(entity.getLowerPrice());
			vo.setStartTime(entity.getStartTime());
			vo.setToAir(entity.getToAir());
			vo.setToCity(entity.getToCity());
			vo.setToCityCode(entity.getToCityCode());
			vo.setTransitFullName(entity.getCarrierFullName());
			vo.setTransitName(entity.getCarrierName());
			vo.setTransitCarrierKey(entity.getCarrierKey());
		    vo.setFlightNo(entity.getFlightNo());
			transitVOList.add(vo);
		   
		   
	   }
	   return transitVOList;
	      
   }


@Override
public List<PlaneInfo> findByCustomFilters(String tableName,
		String startRowKey, String endRowKey, List<HBaseFilterVO> voList,
		List<Filter> filterList) {
	//如果是查询LP_FLIGHT及LP_FLIGHT_HISTORY数据则先查询LP_FLIGHT_DATE
	List<PlaneInfo> list = new ArrayList<PlaneInfo>();
	List<PlaneInfo> yesterdayList = new ArrayList<PlaneInfo>();
	
	FreightPriceEntity entity = new FreightPriceEntity();
	if(tableName.indexOf("LP_FLIGHT_DATE")!=-1){
		String[] tableArray = tableName.split("@"); 
		//查询lp_flight_history
		if(tableArray[1].indexOf("LP_FLIGHT_HISTORY")!=-1){
			List<PlaneInfo> currentPlane = findByConditionsToPlaneInfo(tableArray[1],startRowKey,endRowKey,voList,filterList);
			if(StringUtils.checkList(currentPlane)){
				list = currentPlane;
			}
			//获得昨天的航班
			String yesterdayStartRowKey = this.getYesterdayRowKey(tableName,startRowKey);
			String yesterdayEndRowKey = this.getYesterdayRowKey(tableName,endRowKey);
			List<PlaneInfo> yesterdayPlane = findByConditionsToPlaneInfo(tableArray[1],yesterdayStartRowKey,yesterdayEndRowKey,voList,filterList);
			if(StringUtils.checkList(yesterdayPlane)){
				yesterdayList = yesterdayPlane;
			}
		}else{//查询lp_flight
			List<String> rowKeyList =  this.getLP_FLIGTH_DATE(tableArray[0], startRowKey, endRowKey, voList, filterList);
			for (String rowKey : rowKeyList) {
				//获得当天的航班
				List<PlaneInfo> currentPlane = findByConditionsToPlaneInfo(tableArray[1],rowKey,rowKey,voList,filterList);
				if(StringUtils.checkList(currentPlane)){
					list.add(currentPlane.get(0));
				}
				//获得昨天的航班
				String yesterdayStartRowKey = this.getYesterdayRowKey(tableName,rowKey);
				String yesterdayEndRowKey = this.getYesterdayRowKey(tableName,rowKey);
				List<PlaneInfo> yesterdayPlane = findByConditionsToPlaneInfo(tableArray[1],yesterdayStartRowKey,yesterdayEndRowKey,voList,filterList);
				if(StringUtils.checkList(yesterdayPlane)){
					yesterdayList.add(yesterdayPlane.get(0));
				}
			}	
		}
		
		
	}else{
		String yesterdayStartRowKey = this.getYesterdayRowKey(tableName,startRowKey);
		String yesterdayEndRowKey = this.getYesterdayRowKey(tableName,endRowKey);
		yesterdayList = this.findByConditionsToPlaneInfo(tableName, yesterdayStartRowKey, yesterdayEndRowKey,voList, filterList);
		list =  this.findByConditionsToPlaneInfo(tableName,startRowKey,endRowKey,voList, filterList);
	}
	
	return this.getTendencyList(list, yesterdayList);
	
}

private List<PlaneInfo> getTendencyList(List<PlaneInfo> list,List<PlaneInfo> yesterdayList){
	Map<String,List<CabinEntityVO>> map = new HashMap<String, List<CabinEntityVO>>();
	if(yesterdayList != null && yesterdayList.size()>0){
		for (PlaneInfo planeInfo : list) {
			String currentHour = planeInfo.getFlightBatchStartTime().substring(8, 10);	
			String currentFlightNo = planeInfo.getFlightId();
			double cPrice = Double.parseDouble(planeInfo.getLowerPrice());
			boolean isFlightNoEqual = false;
			for(PlaneInfo yesterdayPlane : yesterdayList){
				double yPrice = Double.parseDouble(yesterdayPlane.getLowerPrice());//昨天最低价
				String yflightHour= yesterdayPlane.getFlightBatchStartTime().substring(8, 10);//20130722150000->2013072215
				String yFlightNo = yesterdayPlane.getFlightId();
				if(yFlightNo.equals(currentFlightNo) && yflightHour.equals(currentHour)){
					isFlightNoEqual = true;
					if(cPrice < yPrice){
						//小于前一天,下降
						planeInfo.setTendency(GlobalsConst.PRICE_STATUS_DESCEND);
					}else if(cPrice > yPrice){
						//大于前一天,上升
						planeInfo.setTendency(GlobalsConst.PRICE_STATUS_ASCEND);
					}else {
						//等于前一天,持平
						planeInfo.setTendency(GlobalsConst.PRICE_STATUS_MAINTAIN);
					}
				}
					
			}
			if(isFlightNoEqual==false){
				planeInfo.setTendency(GlobalsConst.PRICE_STATUS_MAINTAIN);
			}
		
		}
	}else{
		//没有数据运价走势持平
			
			for (PlaneInfo planeInfo : list) {
			planeInfo.setTendency(GlobalsConst.PRICE_STATUS_MAINTAIN);
		}
	}
	
	
	//对仓位重新组织，将cabin_type一样的仓位归类
	for (PlaneInfo planeInfo : list) {
		List<CabinEntityVO> cabins = planeInfo.getCabins();
		if(cabins != null && cabins.size()>0){
			for (CabinEntityVO cabinEntityVO : cabins) {
				if(map.containsKey(cabinEntityVO.getCabinType())){
					map.get(cabinEntityVO.getCabinType()).add(cabinEntityVO);
				}else{
					List<CabinEntityVO> putList = new ArrayList<CabinEntityVO>();
					putList.add(cabinEntityVO);
					map.put(cabinEntityVO.getCabinType(), putList);
				}
			}
		}
		
		//重新放到
		Set<Map.Entry<String, List<CabinEntityVO>>> set = map.entrySet();
        for (Iterator<Map.Entry<String, List<CabinEntityVO>>> it = set.iterator(); it.hasNext();) {
            Map.Entry<String, List<CabinEntityVO>> entry = (Map.Entry<String, List<CabinEntityVO>>) it.next();
            planeInfo.getClassifyCabins().add(entry.getValue());
        }		
		map.clear();
	}
	
	
	return list;
}



private String getYesterdayRowKey(String tableName,String rowKey){
	String table = "";
	String flightDateStr = "";
	String returnDateStr = "";
	if(tableName.indexOf("@")!=-1){//查询LP_FLIGHT或LP_FLIGHT_HISTORY
		String[] tableArray = tableName.split("@");
		//获得表名
		table = tableArray[1];
		//根据表名截取航班日期
		if(table.equalsIgnoreCase("LP_FLIGHT")){
			flightDateStr = rowKey.substring(19, 27);
			
			return   rowKey.substring(0,19)+this.getDate(flightDateStr)+rowKey.substring(27);
		}else if(table.equalsIgnoreCase("LP_FLIGHT_HISTORY")){
			flightDateStr = rowKey.substring(13, 21);
			return   rowKey.substring(0,13)+this.getDate(flightDateStr)+rowKey.substring(21);
		}
	}else if(tableName.indexOf("DOUBLE")!=-1){
			if(tableName.equals("LP_FLIGHT_DOUBLE")){
				//返程航班
				flightDateStr = rowKey.substring(11, 19);
				returnDateStr = rowKey.substring(19, 27);
				return   rowKey.substring(0,11)+this.getDate(flightDateStr)+this.getDate(returnDateStr)+rowKey.substring(27);
			}else if(tableName.equals("LP_FLIGHT_HISTORY_DOUBLE")){
				
			}
		 	

	}
	return null;
}
/**
 * 将日期减一天
 * @param flightStr
 * @return
 */
private String getDate(String flightStr){
	String yesterDate = null;
	Calendar cal = Calendar.getInstance();
	Date flightDate = DateUtils.StringToDate("yyyyMMdd", flightStr);
	cal.setTime(flightDate);
	cal.add(Calendar.DAY_OF_MONTH, -1);
	yesterDate = DateUtils.formatDay(cal.getTime(), "yyyyMMdd");
	//return rowKey.substring(0, 21)+yesterDate.substring(0,8)+rowKey.substring(28);
	return yesterDate;
}
private List<String> getLP_FLIGTH_DATE(String tableName,
		String startRowKey, String endRowKey, List<HBaseFilterVO> voList,
		List<Filter> filterList){
	//List<PlaneInfo> returnList = new ArrayList<PlaneInfo>();
	//String[] tableArray = tableName.split("@"); 
	List<String> rowKeyList  = this.findHbaseKey(tableName, startRowKey, endRowKey, voList, filterList);
	
	return rowKeyList;
}

public List<String> findHbaseKey(String tableName,
		String startRowKey, String endRowKey, List<HBaseFilterVO> voList,
		List<Filter> filterList){
	    HbaseManager hbaseManager = null;
		try {
	    	 hbaseManager = InstanceFactory.getInstance(HbaseManager.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<String> returnList = new ArrayList<String>();
		List<HBaseRowModel> list = null;
		try {
			//获得多个HBaseRowModel,HBaseRowModel相当于一行
			list = hbaseManager.getMultRecordByConditions(tableName, startRowKey, endRowKey, voList, filterList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	    for (HBaseRowModel model : list) {
	    	Set<HBaseCellModel> cellSet = model.getCells();
	    	for (HBaseCellModel hBaseCellModel : cellSet) {
	    		returnList.add(hBaseCellModel.getValue());
			}
		}
	return returnList;
}
 
 public List<PlaneInfo> findByConditionsToPlaneInfo(String tableName,
		String startRowKey, String endRowKey, List<HBaseFilterVO> voList,
		List<Filter> filterList){
	 HbaseManager hbaseManager = null;
		try {
	    	 hbaseManager = InstanceFactory.getInstance(HbaseManager.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		List<HBaseRowModel> list = null;
		try {
			//获得多个HBaseRowModel,HBaseRowModel相当于一行
			list = hbaseManager.getMultRecordByConditions(tableName, startRowKey, endRowKey, voList, filterList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//---------------------------------------------------------------------
		List<PlaneInfo> result = new ArrayList<PlaneInfo>();
		String qualifier,value,family;
		String[] agentInfoKey;
		String[] cabinInfoKey;
		String[] stopOverInfoKey;
		String[] transitsInfoKey;
		for (HBaseRowModel model : list) {
			
			//获得去程代理商
			List<AgentInfo> agents = new ArrayList<AgentInfo>();
			Map<String,AgentInfo> agentMap = new HashMap<String, AgentInfo>();
			
			//获得去程舱位
			List<CabinEntityVO> cabins = new ArrayList<CabinEntityVO>();
			Map<String,CabinEntityVO> cabinsMap = new HashMap<String, CabinEntityVO>();
			
			//获得去程经停城市
			List<StopOverEntityVO> stopOverEntityVOs = new ArrayList<StopOverEntityVO>();
			Map<String,StopOverEntityVO> stopOverEntityMap = new HashMap<String, StopOverEntityVO>();
			
			//获得去程中转
			List<TransitchangeEntityVO> transitEntityVOs = new ArrayList<TransitchangeEntityVO>();
			Map<String,TransitchangeEntityVO> transitchangeEntityMap = new HashMap<String, TransitchangeEntityVO>();
			
			//获得舱位关系
			List<CabinRelationEntityVO> cabinRelationEntityVOs = new ArrayList<CabinRelationEntityVO>();
			Map<String,CabinRelationEntityVO> cabinRelationEntityMap = new HashMap<String, CabinRelationEntityVO>();
			
			
			 Map<String,PlaneInfo> returnPlaneInfoMap = new HashMap<String, PlaneInfo>();
			 Map<String,CabinEntityVO> returnCabinMap = new HashMap<String,CabinEntityVO>();
			 Map<String,StopOverEntityVO> returnStopOverMap = new HashMap<String, StopOverEntityVO>();
			 Map<String,TransitchangeEntityVO> returnTransitMap = new HashMap<String, TransitchangeEntityVO>();
			 Map<String,AgentInfo> returnAgentInfoMap = new HashMap<String, AgentInfo>();
			
			
			PlaneInfo planeInfo = new PlaneInfo();
			try {
				//组装数据为planeinfo对象
				for (HBaseCellModel cell : model.getCells()) {
					 qualifier = new String(cell.getQualifier().getBytes(),"utf-8");
					 family = new String(cell.getFamily().getBytes(),"utf-8");
					 value = new String(cell.getValue().getBytes(), "utf-8");
					if ("planeinfo".equals(family)) {
						Method method = planeInfoMethods.get("set" + qualifier.substring(0, 1).toUpperCase()+ qualifier.substring(1));
						if(null != method){
							try{
								method.invoke(planeInfo, value);
							} catch (Exception e) {
								logger.error(e.getMessage());
							}
						}
					}else if ("agentInfos".equals(family)) {
						agentInfoKey = cell.getQualifier().split("_");
						String property = agentInfoKey[0];
						String str = agentInfoKey[1];
						Method method = agentMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!agentMap.containsKey(str)) {
								agentMap.put(str, new AgentInfo());
							}
							if (agentMap.keySet().contains(str)) 
								try{
									method.invoke(agentMap.get(str),cell.getValue());
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
					}else if("cabinsInfo".equals(family)){
						cabinInfoKey = cell.getQualifier().split("_");
						String property = cabinInfoKey[0];
						String number = cabinInfoKey[1];
						Method method = cabinMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!cabinsMap.containsKey(number)) {
								cabinsMap.put(number, new CabinEntityVO());
							}
							if (cabinsMap.keySet().contains(number)) 
								try{
									if(property!=null && property.indexOf("price")!=-1){
										method.invoke(cabinsMap.get(number),cell.getValue()==null?0.0:Double.parseDouble(cell.getValue()));
									}else{
										method.invoke(cabinsMap.get(number),cell.getValue());
										
									}
									
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
						
					}else if("stopOversInfo".equals(family)){
						stopOverInfoKey = cell.getQualifier().split("_");
						String property = stopOverInfoKey[0];
						String number = stopOverInfoKey[1];
						Method method = stopOverMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!stopOverEntityMap.containsKey(number)) {
								stopOverEntityMap.put(number, new StopOverEntityVO());
							}
							if (stopOverEntityMap.keySet().contains(number)) 
								try{
									method.invoke(stopOverEntityMap.get(number),cell.getValue());
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
					}else if("transitsInfo".equals(family)){
						transitsInfoKey = cell.getQualifier().split("_");
						String property = transitsInfoKey[0];
						String number = transitsInfoKey[1];
						Method method = transitMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!transitchangeEntityMap.containsKey(number)) {
								transitchangeEntityMap.put(number, new TransitchangeEntityVO());
							}
							if (transitchangeEntityMap.keySet().contains(number)) 
								try{
									method.invoke(transitchangeEntityMap.get(number),cell.getValue());
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
					}else if("returnPlaneInfosInfo".equals(family)){//若有返程航班，则生成返程航班保存到map中，key为
						String[] returnFamilyInfo = cell.getQualifier().split("_");
						String property = returnFamilyInfo[0];
						String number = returnFamilyInfo[1];
						Method method = planeInfoMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!returnPlaneInfoMap.containsKey(number)) {
								returnPlaneInfoMap.put(number, new PlaneInfo());
							}
							if (returnPlaneInfoMap.keySet().contains(number)) 
								try{
									method.invoke(returnPlaneInfoMap.get(number),cell.getValue());
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
						
					}else if("returnAgentsInfo".equals(family)){//若有返程航班，则生成返程航班保存到map中，key为
						String[] returnFamilyInfo = cell.getQualifier().split("_");
						String property = returnFamilyInfo[0];
						String parentNum = returnFamilyInfo[1];
						String agentNum = returnFamilyInfo[2]; 
						Method method = agentMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!returnAgentInfoMap.containsKey(parentNum+"_"+agentNum)) {
								returnAgentInfoMap.put(parentNum+"_"+agentNum, new AgentInfo());
							}
							if (returnAgentInfoMap.keySet().contains(parentNum+"_"+agentNum)) 
								try{
									method.invoke(returnAgentInfoMap.get(parentNum+"_"+agentNum),cell.getValue());
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
						
					}else if("returnCabinsInfo".equals(family)){//若有返程航班，则生成返程航班保存到map中，key为
						String[] returnFamilyInfo = cell.getQualifier().split("_");
						String property = returnFamilyInfo[0];
						String parentNum = returnFamilyInfo[1];
						String cabinNum = returnFamilyInfo[2]; 
						Method method = cabinMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!returnCabinMap.containsKey(parentNum+"_"+cabinNum)) {
								returnCabinMap.put(parentNum+"_"+cabinNum, new CabinEntityVO());
							}
							if (returnCabinMap.keySet().contains(parentNum+"_"+cabinNum)) 
								try{
									if(property!=null && property.indexOf("price")!=-1){
										method.invoke(returnCabinMap.get(parentNum+"_"+cabinNum),cell.getValue()==null?null:Double.parseDouble(cell.getValue()));
									}else{
										method.invoke(returnCabinMap.get(parentNum+"_"+cabinNum),cell.getValue());
									}
									
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
						
					}else if("returnStopOversInfo".equals(family)){//若有返程航班，则生成返程航班保存到map中，key为
						String[] returnFamilyInfo = cell.getQualifier().split("_");
						String property = returnFamilyInfo[0];
						String parentNum = returnFamilyInfo[1];
						String stopOverNum = returnFamilyInfo[2]; 
						Method method = stopOverMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!returnCabinMap.containsKey(parentNum+"_"+stopOverNum)) {
								returnStopOverMap.put(parentNum+"_"+stopOverNum, new StopOverEntityVO());
							}
							if (returnStopOverMap.keySet().contains(parentNum+"_"+stopOverNum)) 
								try{
									method.invoke(returnStopOverMap.get(parentNum+"_"+stopOverNum),cell.getValue());
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
						
					}else if("returnTransitsInfo".equals(family)){//若有返程航班，则生成返程航班保存到map中
						String[] returnFamilyInfo = cell.getQualifier().split("_");
						String property = returnFamilyInfo[0];
						String parentNum = returnFamilyInfo[1];
						String transitNum = returnFamilyInfo[2]; 
						Method method = transitMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!returnTransitMap.containsKey(parentNum+"_"+transitNum)) {
								returnTransitMap.put(parentNum+"_"+transitNum, new TransitchangeEntityVO());
							}
							if (returnTransitMap.keySet().contains(parentNum+"_"+transitNum)) 
								try{
									method.invoke(returnTransitMap.get(parentNum+"_"+transitNum),cell.getValue());
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
						
					}else if("cabinRelationsInfo".equals(family)){//若有返程航班，则生成返程航班保存到map中
						String[] cabinRelationsInfo = cell.getQualifier().split("_");
						String property = cabinRelationsInfo[0];
						String number = cabinRelationsInfo[1];
						Method method = cabinRelationMethods.get("set"+ property.substring(0, 1)
								.toUpperCase()+ property.substring(1));
						if (null != method) {
							if (!cabinRelationEntityMap.containsKey(number)) {
								cabinRelationEntityMap.put(number, new CabinRelationEntityVO());
							}
							if (cabinRelationEntityMap.keySet().contains(number)) 
								try{
										method.invoke(cabinRelationEntityMap.get(number),cell.getValue());
								} catch (Exception e) {
									logger.error(e.getMessage());
								}
						}
						
					}
				}
				
				agents.addAll(agentMap.values());
				cabins.addAll(cabinsMap.values());
				stopOverEntityVOs.addAll(stopOverEntityMap.values());
				transitEntityVOs.addAll(transitchangeEntityMap.values());	
				cabinRelationEntityVOs.addAll(cabinRelationEntityMap.values());
				
				
				//组织去程信息
				planeInfo.setAgentInfos(agents);
				planeInfo.setCabins(cabins);
				
				planeInfo.setTransit(transitEntityVOs);
				planeInfo.setStopOverlist(stopOverEntityVOs);
				planeInfo.setCabinRelations(cabinRelationEntityVOs);
				
				
				//组织返程航班信息
				if(returnPlaneInfoMap != null && returnPlaneInfoMap.size() > 0){
					List<PlaneInfo> returnPlaneInfo = getReturnPlaneInfo(returnPlaneInfoMap,returnCabinMap,returnStopOverMap,returnTransitMap,returnAgentInfoMap);
					planeInfo.setReturnPlaneInfo(returnPlaneInfo);
				}	
				result.add(planeInfo);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return result; 
}
	private List<PlaneInfo>  getReturnPlaneInfo(Map<String,PlaneInfo> returnPlaneInfoMap,  Map<String,CabinEntityVO> returnCabinMap, Map<String,StopOverEntityVO> returnStopOverMap, Map<String,TransitchangeEntityVO> returnTransitMap, Map<String,AgentInfo> returnAgentInfoMap){
		if (returnCabinMap != null && returnCabinMap.size() > 0) {
			for (String key : returnCabinMap.keySet()) {
				returnPlaneInfoMap.get(key.split("_")[0]).getCabins()
						.add(returnCabinMap.get(key));
			}
		}

		if (returnStopOverMap != null && returnStopOverMap.size() > 0) {
			for (String key : returnStopOverMap.keySet()) {
				returnPlaneInfoMap.get(key.split("_")[0]).getStopOverlist()
						.add(returnStopOverMap.get(key));
			}
		}

		if (returnTransitMap != null && returnTransitMap.size() > 0) {
			for (String key : returnTransitMap.keySet()) {
				returnPlaneInfoMap.get(key.split("_")[0]).getTransit()
						.add(returnTransitMap.get(key));
			}
		}

		if (returnAgentInfoMap != null && returnAgentInfoMap.size() > 0) {

			for (String key : returnAgentInfoMap.keySet()) {
				returnPlaneInfoMap.get(key.split("_")[0]).getAgentInfos()
						.add(returnAgentInfoMap.get(key));
			}
		}

		List<PlaneInfo> returnList = new ArrayList<PlaneInfo>();
		returnList.addAll(returnPlaneInfoMap.values());
		return returnList;
	}
	
	
	
}

